package JUC_Advanced.chapter1_CompletableFuture.api;

import JUC_Advanced.ThreadPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author: GuSongLiao
 * @Date: 2024/3/7 10:53
 * @Description: api deno
 */

/**
 * acceptEither 两个任务同时执行，某一个执行完毕后，直接获取结果
 */
public class CompletableFutureApi_acceptEither {

    public static void main(String[] args) {

        /**
         * 需求如下，两个玩家 PK，谁速度快选谁
         */
        CompletableFuture<String> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("player A come in -------");
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            return "player A";
        }, ThreadPool.THREAD_POOL);

        CompletableFuture<String> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("player B come in -------");
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            return "player B";
        }, ThreadPool.THREAD_POOL);

        // 重要API
        playA.acceptEither(playB, winner -> System.out.println(winner + " win!"));


        System.out.println("主线程忙别的去了");
    }
}
